//
//  CZDetailViewController.m
//  QQ空间
//
//  Created by zhangping on 16/1/19.
//  Copyright © 2016年 zhangping. All rights reserved.
//

#import "CZDetailViewController.h"
#import "CZMenuItem.h"

@interface CZDetailViewController ()

/// 正在显示的控制器
@property (nonatomic, strong) UINavigationController *showViewController;

@property (nonatomic, strong) CZMenuItem *menuItem;

@end

@implementation CZDetailViewController

/**
 *  显示详情控制器
 *  @param item item模型
 */
- (void)showControllerWithMenuItem:(CZMenuItem *)menuItem {
    // 移除正在显示的控制器的view
    [self.showViewController.view removeFromSuperview];
    
    BOOL hasVC = NO;
    // 判断子控制器是否已经存在
    for (UIViewController *vc in self.childViewControllers) {
        if ([vc.title isEqualToString:menuItem.title]) {
            hasVC = YES;
            self.showViewController = (UINavigationController *)vc;
            break;
        }
    }
    
    if (!hasVC) {
        Class cls = NSClassFromString(menuItem.detailVCClassName);
        // 创建根控制器
        UIViewController *vc = [[cls alloc] init];
        
        // 设置导航栏标题
        vc.title = menuItem.title;
        
        // 包装导航控制器
        self.showViewController = [[UINavigationController alloc] initWithRootViewController:vc];
        
        // 将根控制器添加为当前详情控制器的子控制器
        [self addChildViewController:self.showViewController];
    }
    
    // 将根控制器的view添加到当前详情控制器的view里面
    [self.view addSubview:self.showViewController.view];
    
    // 设置rootViewController的view的布局
    [self.showViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(20, 0, 0, 44));
    }];
    
    CZLog(@"self.menuItem.title: %@", menuItem.title);
    CZLog(@"subView Count: %zd", self.view.subviews.count);
    CZLog(@"childController Count: %zd", self.childViewControllers.count);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置详情控制器的背景颜色
    self.view.backgroundColor = CZCommonBGColor;
}

- (void)dealloc {
    CZLog(@"详情控制器销毁了");
}

@end
